package com.example.captcha.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-17
 * Time: 0:17
 */
@RestController
@RequestMapping("/admin")
public class CaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "ADMIN_KAPTCHA_SESSION_KEY";
    private static final Long SESSION_TIMEOUT = 60*1000L;//ms 有效时间
    private static final String KAPTCHA_SESSION_DATE = "ADMIN_KAPTCHA_SESSION_DATE";
    /**
     * 从session中获取生成验证码
     * 比对前端传递的验证码和后端生成的是否相同
     * @param captcha
     * @return
     */
    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            System.out.println(111);
            return false;
        }
        String save = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);
        if (save.equals(captcha)) {
            //比对日期
            System.out.println((saveDate == null || System.currentTimeMillis() - saveDate.getTime() < SESSION_TIMEOUT));
            return saveDate == null || System.currentTimeMillis() - saveDate.getTime() < SESSION_TIMEOUT;
        }
        System.out.println(1111);
        return false;
    }
}
